package com.woniu.util;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Locale;

public class PasswordHasher {
    private static final BCryptPasswordEncoder BCRYPT = new BCryptPasswordEncoder();

    public static boolean matches(String rawPassword, String dbPassword, String salt) {
        if (dbPassword == null) return false;
        String pwd = rawPassword == null ? "" : rawPassword;

        // 1) BCrypt
        if (isBCrypt(dbPassword)) {
            return BCRYPT.matches(pwd, dbPassword);
        }
        // 2) 旧方案：SHA-256(salt + password)
        if (salt != null && !salt.trim().isEmpty()) {
            String sha256 = sha256Hex(salt + pwd);
            return dbPassword.equalsIgnoreCase(sha256);
        }
        // 3) 明文兜底（仅兼容历史数据，建议尽快迁移到 BCrypt）
        return dbPassword.equals(pwd);
    }

    public static String bcrypt(String rawPassword) {
        return BCRYPT.encode(rawPassword);
    }

    private static boolean isBCrypt(String s) {
        return s.startsWith("$2a$") || s.startsWith("$2b$") || s.startsWith("$2y$");
    }

    private static String sha256Hex(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] dig = md.digest(s.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder(dig.length * 2);
            for (byte b : dig) {
                sb.append(String.format(Locale.ROOT, "%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new IllegalStateException("SHA-256 not available", e);
        }
    }
}